package com.cxx.purchasecharge.component.controller.auditlog;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.auditlog.LogEventTypeBean;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.auditlog.LogEventType;
import com.cxx.purchasecharge.dal.auditlog.LogEventTypeDao;

@Controller
@RequestMapping ("/logEventType")
public class LogEventTypeController
{
    private static final Logger logger = Logger.getLogger (LogEventTypeController.class);

    @Autowired
    private LogEventTypeDao logEventTypeDao;

    @RequestMapping (value = "/")
    public String redirectToLogEventTypeManagement (ModelMap model)
    {
        return "logEventTypeManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String logEventTypeId, @RequestParam String name)
    {
        if (StringUtils.isBlank (logEventTypeId))
        {
            // new
            LogEventType obj = logEventTypeDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (logEventTypeId);
            LogEventType logEventType = logEventTypeDao.findByName (name);
            if (null != logEventType && logEventType.getId () != id)
            {
                return "false";
            }
        }

        return "true";
    }

    @RequestMapping (value = "/getAllEventType", method = RequestMethod.POST)
    public @ResponseBody
    String getLogEventTypes (DataGridRequestForm dataGridRequestForm)
    {
        List <LogEventType> logEventTypes = (List <LogEventType>) logEventTypeDao.findAll ();

        JSONArray jsonObject = JSONArray.fromObject (logEventTypes);
        return jsonObject.toString ();
    }

    @RequestMapping (value = "/newEventType", method = RequestMethod.POST)
    public @ResponseBody
    String addLogEventType (LogEventTypeBean logEventTypeBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            LogEventType logEventType = new LogEventType (logEventTypeBean.getName ());
            logEventType.setPattern (logEventTypeBean.getPattern ());
            logEventType.setEnable (logEventTypeBean.isEnable ());

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                logEventTypeDao.save (logEventType);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateEventType", method = RequestMethod.POST)
    public @ResponseBody
    String updateLogEventType (LogEventTypeBean logEventTypeBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            LogEventType logEventType = new LogEventType (logEventTypeBean.getName ());
            logEventType.setPattern (logEventTypeBean.getPattern ());
            logEventType.setEnable (logEventTypeBean.isEnable ());
            logEventType.setId (StringUtils.isNotBlank (logEventTypeBean.getId ()) ? Long.parseLong (logEventTypeBean.getId ())
                                                                                  : 0);

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                logEventTypeDao.save (logEventType);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/delEventType", method = RequestMethod.POST)
    public @ResponseBody
    String deleteLogEventType (@RequestParam String ids)
    {
        if (StringUtils.isNotBlank (ids))
        {
            List <LogEventType> logEventTypes = new ArrayList <LogEventType> ();
            LogEventType logEventType;
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String typeId : idArr)
                {
                    logEventType = new LogEventType ();
                    logEventType.setId (Long.parseLong (typeId));
                    logEventTypes.add (logEventType);
                }
            }
            else
            {
                logEventType = new LogEventType ();
                logEventType.setId (Long.parseLong (ids));
                logEventTypes.add (logEventType);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                logEventTypeDao.delete (logEventTypes);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_LOG_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }
}
